package com.zxj.netty.client;

import com.alibaba.fastjson.JSONObject;
import com.zxj.netty.annotation.RpcReference;
import com.zxj.netty.annotation.SystemAlias;
import com.zxj.netty.model.NettyRequest;
import com.zxj.netty.model.NettyResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 消费端引用远程服务时，获取远程服务的代理类进行调用
 */
@Component
public class RemoteInvokerProxy implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 对引用的远程服务设置代理
            if (field.isAnnotationPresent(RpcReference.class) && field.getType().isInterface()) {
                field.setAccessible(true);

                try {
                    // 设置该实例被RpcReference注解的成员变量值为相应代理
                    field.set(o, ProxyFactory.getJdkProxy(field.getType()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        return o;
    }
}
